package controller

import (
	"blog/dao"
	"github.com/julienschmidt/httprouter"
	"html/template"
	"net/http"
	"strconv"
	"sync"
)

func IndexHandle(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	dao.CommonAction(r, w)
	//页号
	pageId, err := strconv.ParseInt(r.URL.Query().Get("page"), 10, 64)
	if err != nil {
		pageId = 1
	}
	if pageId < 1 {
		pageId = 1
	}

	//首页返回数据-数据结构
	type IndexPageReturnData struct {
		PostList dao.PostListData `json:"posts"` //文章列表
		LinkList []dao.Link       `json:"links"` //外链列表
		TagList  []dao.TagData    `json:"tags"`  //标签列表
	}
	var R IndexPageReturnData
	var wg sync.WaitGroup

	wg.Add(3)

	//获取链接列表
	go func() {
		R.LinkList, _ = dao.GetLinks(0)
		wg.Done()
	}()

	//获取标签列表
	go func() {
		R.TagList = dao.GetTagList("rand", dao.TagListPageSize)
		wg.Done()
	}()

	//获取文章列表
	go func() {
		R.PostList = dao.GetPostList(pageId, dao.IndexPageSize, 0, false)
		wg.Done()
	}()
	wg.Wait()

	t, err := template.New("index.html").Funcs(dao.FuncMap).ParseFiles("templates/index.html", "templates/pub_inc.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	t.Execute(w, R)
}
